package com.km.wskj.itmonitor.pager.wq.parts;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.model.Imgs;
import com.km.wskj.itmonitor.model.PartsColumn;
import com.km.wskj.itmonitor.model.PartsItem;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/3/21.
 */
//培训专区主页面
public class PartsActivity extends LActivity implements StateLayout.OnViewRefreshListener {
    private static final String TAG = "PartsActivity";
    //ui
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right)
    ImageView toolBarRight;
    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;

    LinearLayout mContainer;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;

    //data
    private List<String> imgUrls = new ArrayList<>();
    private MyGridView gridView;
    List<FuncItem> funcItems = new ArrayList<>();
    private MyAdapter mAdapter;
    private int pageIndex;
    private int lastUpdateNum;
    private List<PartsItem> mPartsGoods;
    private Intent intent;

    private List<PartsColumn> partsColumns;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wq_parts);
        ButterKnife.bind(this);
        stateLayout.setRefreshListener(this);
        toolBarTitle.setText("配件商城");
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRight.setVisibility(View.VISIBLE);
        toolBarRight.setImageResource(R.mipmap.search_white);

        initData();
    }

    private void initData() {
        stateLayout.showLoadingView();
        initFuncItems();
        pdc.partsColumn(HTTP_TASK_TAG, null, new ZxlGenericsCallback<List<PartsColumn>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<PartsColumn> pcs, int i) {
                partsColumns = pcs;
            }
        });

        pdc.goodsList(HTTP_TASK_TAG, null, 1, Constant.PageListSize, new ZxlGenericsCallback<List<PartsItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<PartsItem> pg, int i) {
                mPartsGoods = pg;
                lastUpdateNum = pg.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });

        initPullToRefresh();
    }


    private void initFuncItems() {
        String s[] = getResources().getStringArray(R.array.wq_parts_func_title);
        int r[] = {R.mipmap.monitor_internet
                , R.mipmap.monitor_knife_box
                , R.mipmap.monitor_memory
                , R.mipmap.monitor_safe
                , R.mipmap.all
        };
        funcItems.clear();
        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            funcItems.add(fi);
        }
    }

    private void createGridView() {

        gridView = new MyGridView(context, new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 5;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return mContainer.getHeight() / 1;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return mContainer.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = getLayoutInflater().inflate(R.layout.ws_college_item_func, null);
                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);

                FuncItem fi = funcItems.get(i);
                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);
                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return false;
            }
        });


        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {
                switch (i) {
                    //网络配件
                    case 0: {
                        PartsColumn item = getCurrentItem("网络配件");
                        intent = new Intent(context, PartsTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //刀箱备件
                    case 1: {
                        PartsColumn item = getCurrentItem("刀箱备件");
                        intent = new Intent(context, PartsTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //存储备件
                    case 2: {
                        PartsColumn item = getCurrentItem("存储备件");
                        intent = new Intent(context, PartsTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //小型机备件
                    case 3: {
                        PartsColumn item = getCurrentItem("小型机备件");
                        intent = new Intent(context, PartsTabListActivity.class);
                        intent.putExtra("data", item);
                        startActivity(intent);
                    }
                    break;
                    //全部
                    case 4: {
                        openIntent(PartsClassifyActivity.class, true);
                    }
                    break;
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mContainer.addView(gridView.getView(), p);
    }


    private void initPullToRefresh() {
        //添加头布局
        View view = getLayoutInflater().inflate(R.layout.header_parts, null);
        mContainer = (LinearLayout) view.findViewById(R.id.container);
        mContainer.removeAllViews();
        initFuncItems();

        mContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });
        if (mZrcListView.getHeaderViewsCount() == 0)
            mZrcListView.addHeaderView(view, null, true);//注意：第三个参数必须为true，否则无效

        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                PartsItem item = (PartsItem) parent.getItemAtPosition(position);
                Intent t = new Intent(context, PartsDetailActivity.class);
                t.putExtra("id", item.id);
                startActivity(t);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);

        stateLayout.showContentView();
    }

    private void onRefresh() {
        pdc.goodsList(HTTP_TASK_TAG, null, 1, Constant.PageListSize, new ZxlGenericsCallback<List<PartsItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mZrcListView.setRefreshFail("数据获取失败");
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<PartsItem> pg, int i) {
                mPartsGoods = pg;
                lastUpdateNum = pg.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private void onLoadMore() {
        pdc.goodsList(HTTP_TASK_TAG, null, pageIndex + 1, Constant.PageListSize, new ZxlGenericsCallback<List<PartsItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mZrcListView.setRefreshFail("数据获取失败");
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<PartsItem> pg, int i) {

                lastUpdateNum = pg.size();
                if (pg.size() > 0) {
                    mPartsGoods.addAll(pg);
                    pageIndex++;
                }
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();

            }
        });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    @Override
    public void refreshClick() {

    }

    @Override
    public void loginClick() {

    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mPartsGoods == null) {
                return 0;
            }
            return mPartsGoods.size();
        }

        @Override
        public Object getItem(int position) {
            return mPartsGoods.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView, parent, R.layout.item_parts_list);
            PartsItem item = mPartsGoods.get(position);
            helper.setText(R.id.tv_title, item.title);
            helper.setText(R.id.tv_des, item.applicableModels);
            helper.setText(R.id.tv_price, "￥" + item.price + "");

            //图片url
            if (item.imgs.size() > 0) {
                Imgs imgs = item.imgs.get(0);
                String url = imgs.host + imgs.file_path + imgs.new_file_name;
                Glide.with(mActivity)
                        .load(url)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_preview, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }
            return helper.getView();
        }
    }

    private PartsColumn getCurrentItem(String itemName) {

        for (PartsColumn pc : partsColumns
                ) {
            if (pc.columnName.equals(itemName))
                return pc;
        }
        return null;
    }

    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right:
                normalToasty("search");
                break;
        }
    }
}
